package com.fire.web.modules.all.service.impl;

import com.fire.common.mybatis.mvc.wrapper.EntityWrapper;
import com.fire.core.util.DateUtil;
import com.fire.web.modules.all.constant.ErrorCodeConstants;
import com.fire.web.modules.all.entity.*;
import com.fire.web.modules.all.mapper.FireSupervisorMapper;
import com.fire.web.modules.all.service.*;
import com.fire.web.modules.all.utils.TokenUtil;
import com.fire.web.modules.all.validation.AssetDTO;
import com.fire.web.modules.sso.service.IOAuthService;
import com.fire.web.security.shiro.realm.UserRealm;
import com.smartthing.rest.model.search.DateRangeSearchCriteria;
import com.smartthing.spi.ISmartThingClient;
import com.smartthing.spi.SmartThingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: StatisticsServiceImpl
 * @Description: TODO
 * @Author raoyuxing
 * @Date 2019/2/25 18:08
 */
@Service
public class StatisticsServiceImpl implements IStatisticsService {



    @Autowired
    private ITMitStaticsSiteService staticsSiteService;

    @Autowired
    private IOAuthService oAuthService;

    @Autowired
    private IFireSupervisorService supervisorService;

    @Autowired
    private ITMitStaticsSuperiorService staticsSuperiorService;

    @Autowired
    private IFireProprietorService fireProprietorService;

    @Autowired
    private ISiteService siteService;

    @Autowired
    private IAssetService assetService;

    @Autowired
    private ISmartThingClient client;

    @Autowired
    private IBuildingService buildingService;

    @Autowired
    private IFireDangrousResouceService dangrousResouceService;


    private static final String[] RANGES = new String[]{"water", "electricity","gas","fire","dvr"};

    /**
     * 功能描述: 获取业主单位统计结果
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/2/25 18:12
     */
    @Override
    public Map<String, Object> proprietorStatistics(HttpServletRequest request, HttpServletResponse response) throws SmartThingException {
        String[] result = getIdByToken(request,response);
        EntityWrapper<TMitStaticsSiteModel> wrapper = new EntityWrapper<>();
        String startDate = DateUtil.getBeforeDayDate(1,"yyyyMMdd");
        String endDate = DateUtil.getBeforeDayDate(7,"yyyyMMdd");
        wrapper.le("seqdate", startDate)
                .ge("seqdate",endDate)
                .eq("siteid",result[0])
                .orderBy("seqdate",false);
        List<TMitStaticsSiteModel> list = staticsSiteService.selectList(wrapper);
        int[] waterDate = new int[7];
        int[] electricityDate = new int[7];
        int[] gasDate = new int[7];
        int[] fireDate = new int[7];
        int waterIndex = 6;
        int electricityIndex = 6;
        int gasIndex = 6;
        int fireIndex = 6;
        int alarm = 0;
        for (TMitStaticsSiteModel site: list) {
            if (RANGES[0].equals(site.getRange())){
                waterDate[waterIndex] = site.getAlarmnum();
                waterIndex--;
            }
            if (RANGES[1].equals(site.getRange())){
                electricityDate[electricityIndex] = site.getAlarmnum();
                electricityIndex--;
            }
            if (RANGES[2].equals(site.getRange())){
                gasDate[gasIndex] = site.getAlarmnum();
                gasIndex--;
            }
            if (RANGES[3].equals(site.getRange())){
                fireDate[fireIndex] = site.getAlarmnum();
                fireIndex--;
            }
            if (site.getSeqdate().equals(startDate)) {
                alarm += site.getAlarmnum();
            }
        }

        Map relist = new HashMap();
        relist.put("waterDate",waterDate);
        relist.put("electricityDate",electricityDate);
        relist.put("gasDate",gasDate);
        relist.put("fireDate",fireDate);


        long device = 0L;
        long asset = 0L;
        EntityWrapper<SiteModel> siteWrapper = new EntityWrapper<>();
        siteWrapper.eq("proprietor",result[2]);
        List<SiteModel> siteList = siteService.selectList(siteWrapper);
        for (SiteModel site: siteList) {
            DateRangeSearchCriteria criteria = new DateRangeSearchCriteria(1, Integer.MAX_VALUE, null, null);
            long devicenum = client.listDevices(site.getSitetoken(),
                    false,false,false,false,
                    criteria).getNumResults();
            device += devicenum;

            AssetDTO assetDTO = new AssetDTO();
            assetDTO.setSiteid(site.getSiteid());
            assetDTO.setPage(1);
            assetDTO.setPagesize(Integer.MAX_VALUE);
            Long assetnum = assetService.getAssetList(assetDTO).getNumResults();
            asset += assetnum;
        }

        Map<String, Object> map = new HashMap<>();

        map.put("datelist",relist);
        map.put("alarm",alarm);
        map.put("device",device);
        map.put("asset",asset);

        return map;
    }

    /**
     * 功能描述: 获取监管单位统计结果
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/2/25 18:12
     */
    @Override
    public Map<String, Object> supervisorStatistics(HttpServletRequest request, HttpServletResponse response) throws SmartThingException {

        String[] result = getIdByToken(request,response);
        String startDate = DateUtil.getBeforeDayDate(1,"yyyyMMdd");
        String endDate = DateUtil.getBeforeDayDate(7,"yyyyMMdd");
        EntityWrapper<TMitStaticsSuperiorModel> wrapper = new EntityWrapper<>();
        wrapper.le("seqdate", startDate)
                .ge("seqdate",endDate)
                .eq("superiorid",result[1]);
        List<TMitStaticsSuperiorModel> list = staticsSuperiorService.selectList(wrapper);
        int[] waterDate = new int[7];
        int[] electricityDate = new int[7];
        int[] gasDate = new int[7];
        int[] fireDate = new int[7];
        int waterIndex = 6;
        int electricityIndex = 6;
        int gasIndex = 6;
        int fireIndex = 6;
        int alarm = 0;
        for (TMitStaticsSuperiorModel superior : list) {
            if (RANGES[0].equals(superior.getRange())){
                waterDate[waterIndex] = superior.getAlarmnum();
                waterIndex--;
            }
            if (RANGES[1].equals(superior.getRange())){
                electricityDate[electricityIndex] = superior.getAlarmnum();
                electricityIndex--;
            }
            if (RANGES[2].equals(superior.getRange())){
                gasDate[gasIndex] = superior.getAlarmnum();
                gasIndex--;
            }
            if (RANGES[3].equals(superior.getRange())){
                fireDate[fireIndex] = superior.getAlarmnum();
                fireIndex--;
            }
            if (superior.getSeqdate().equals(startDate)) {
                alarm += superior.getAlarmnum();
            }
        }

        EntityWrapper<SiteModel> siteWrapper = new EntityWrapper<>();
        siteWrapper.eq("supervisorid",result[1]);
        List<SiteModel> siteList = siteService.selectList(siteWrapper);
        int site = siteList.size();

        EntityWrapper<FireDangrousResouceModel> dangrousResouceWrapper = new EntityWrapper<>();
        dangrousResouceWrapper.eq("supervisorid",result[1]);
        List<FireDangrousResouceModel> dangrousResouceList = dangrousResouceService.selectList(dangrousResouceWrapper);
        int hazards = dangrousResouceList.size();

        EntityWrapper<BuildingModel> buildingWrapper = new EntityWrapper<>();
        buildingWrapper.eq("supervisor",result[1]);
        List<BuildingModel> buildingList = buildingService.selectList(buildingWrapper);
        int building = buildingList.size();

        int subordinate = supervisorService.getSupervisorListById(result[1]).size();

        Map relist = new HashMap();
        relist.put("waterDate",waterDate);
        relist.put("electricityDate",electricityDate);
        relist.put("gasDate",gasDate);
        relist.put("fireDate",fireDate);


        Map<String, Object> map = new HashMap<>();

        map.put("datelist",relist);
        map.put("alarm",alarm);
        map.put("site",site);
        map.put("hazards",hazards);
        map.put("building",building);
        map.put("subordinate",subordinate);


        return map ;
    }


    /**
     * 功能描述: 根据token获取siteid
     * @param: request response
     * @return: siteid
     * @auther: raoyuxing
     * @date: 2019/2/22 14:54
     */
    private String[] getIdByToken(HttpServletRequest request, HttpServletResponse response){

        String token = TokenUtil.getToken(request, response);
        UserRealm.Principal principalByAccessToken = oAuthService.getPrincipalByAccessToken(token);
        String id = principalByAccessToken.getId();

        EntityWrapper<FireProprietorModel> proprietorWrapper = new EntityWrapper<>();
        proprietorWrapper.eq("adminid",id);
        FireProprietorModel proprietor = fireProprietorService.selectOne(proprietorWrapper);

        EntityWrapper<FireSupervisorModel> supervisorWrapper = new EntityWrapper<>();
        supervisorWrapper.eq("adminid",id);
        FireSupervisorModel supervisor = supervisorService.selectOne(supervisorWrapper);

        EntityWrapper<SiteModel> siteWrapper = new EntityWrapper<>();
        siteWrapper.eq("proprietor",proprietor.getProprietor());
        SiteModel site = siteService.selectOne(siteWrapper);

        String[] result = new String[]{site.getSiteid(),supervisor.getSupervisorid(),proprietor.getProprietor()};
        return result;
    }
}
